/**
 * Project Name:viewflip
 * Date:2016-5-31下午12:13:35
 * Copyright (c) 2016, askzhao All Rights Reserved.
 *
 */
package com.kkd.kkdapp.view;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.activity.NoticeDetailActivity;
import com.kkd.kkdapp.db.app.model.Notice;
import com.kkd.kkdapp.db.user.model.KkdMessageModel;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

/**
 * ClassName: VerticalFlipTextView <br/>
 * date: 2016-5-31 下午12:13:35 <br/>
 * 
 * @author askzhao
 * @version
 */
public class VerticalFlipTextView extends RelativeLayout implements
		OnGestureListener {

	public static final int PERIOD = 5000;

	private Context mContext;
	private Animation leftInAnimation;
	private Animation leftOutAnimation;
	private GestureDetector detector; // 手势检测
	private ViewFlipper mViewFlipper;
	private TextView index_notice_tv;
	private TextView index_notice_tv2;
	private int mCurIndex;

	private ArrayList<Notice> mImgList;// 以后扩展注意修改list的泛型
	private ArrayList<TextView> mImgViewList = new ArrayList<TextView>();

	private static final int RECORD_TIMER = 8112;
	private static final int RECORD_DONE = 8113;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	private Timer mTimer = new Timer();
	private TimerTask mTimerTask = null;
	public TimerHandler mTimerHandler = new TimerHandler(this);
	protected boolean onStarting = false;

	private void startFlipBanner() {
		mRecordTime = 0;
		if (mTimerTask == null) {
			mTimerTask = new RecordTimeTask();
			mTimer.schedule(mTimerTask, 0, PERIOD);
		}
		isRecoding = true;

	}

	public static class TimerHandler extends Handler {
		WeakReference<VerticalFlipTextView> reference;

		public TimerHandler(VerticalFlipTextView view) {
			reference = new WeakReference<VerticalFlipTextView>(view);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null) {
					reference.get().toRight();// 向右滑动
				}
				break;
			case RECORD_DONE:
				break;
			default:
				break;
			}
		}
	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				Message message = new Message();
				message.what = RECORD_TIMER;
				message.obj = mRecordTime;
				mTimerHandler.sendMessage(message);
			}

		}
	}

	/**
	 * @param context
	 */
	public VerticalFlipTextView(Context context) {
		super(context);
		init(context);
	}

	/**
	 * @param context
	 * @param attrs
	 */
	public VerticalFlipTextView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);

	}

	/**
	 * @param context
	 * @param attrs
	 * @param defStyle
	 */
	public VerticalFlipTextView(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
		init(context);
	}

	/**
	 * init:(初始化操作). <br/>
	 * 
	 * @author askzhao
	 */
	private void init(Context context) {

		mContext = context;
		View mContentView = RelativeLayout.inflate(mContext,
				R.layout.index_notice_layout, null);
		android.view.ViewGroup.LayoutParams params = new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		addView(mContentView, params);

		mViewFlipper = (ViewFlipper) findViewById(R.id.index_notice_flipper);
		index_notice_tv = (TextView) findViewById(R.id.index_notice_tv);
		index_notice_tv.setTag(0);
		index_notice_tv2 = (TextView) findViewById(R.id.index_notice_tv2);
		index_notice_tv2.setTag(1);
		detector = new GestureDetector(this);

		// 动画效果
		leftInAnimation = AnimationUtils.loadAnimation(mContext,
				R.anim.push_up_in);
		leftOutAnimation = AnimationUtils.loadAnimation(mContext,
				R.anim.push_up_out);

		startFlipBanner();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		detector.onTouchEvent(event); // touch事件交给手势处理。
		return true;
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		return false;
	}

	public void toRight() {
		if (mImgList != null && mImgList.size() > 0) {
			mViewFlipper.setInAnimation(leftInAnimation);
			mViewFlipper.setOutAnimation(leftOutAnimation);
			int position = mViewFlipper.getDisplayedChild();
			String title = mImgList.get(mCurIndex % mImgList.size()).title;
			if (position == 0) {
				index_notice_tv2.setText(title);
			} else {
				index_notice_tv.setText(title);
			}
			mViewFlipper.showNext();// 向右滑动
			mCurIndex = (mCurIndex + 1) % mImgList.size();
		}

	}
	
	private void toFirst() {
		if (mImgList != null && mImgList.size() > 0) {
			int position = mViewFlipper.getDisplayedChild();
			mCurIndex = 0;
			String title = mImgList.get(mCurIndex % mImgList.size()).title;
			index_notice_tv.setText(title);
			if (position == 1) {
				mViewFlipper.showNext();
			}
		}
	}

	@Override
	public void onLongPress(MotionEvent e) {
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		try {
			KkdMessageModel.updateStatusById("已读", mImgList.get(mCurIndex).id);
			Notice.updateStatusById("已读", mImgList.get(mCurIndex).id);
			Intent intent = new Intent(mContext, NoticeDetailActivity.class);
			intent.putExtra("id", mImgList.get(mCurIndex).id);
			mContext.startActivity(intent);
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return false;
	}

	/**
	 * recycle:(当actvity退出时调用此方法回收，避免内存泄漏). <br/>
	 * 
	 * @author askzhao
	 */
	public void recycle() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}

	public void setNotices(ArrayList<Notice> nImgList) {
		mImgList = nImgList;
		notifyDataSetChanged();
	}

	/**
	 * notifyDataSetChanged:(这里用一句话描述这个方法的作用). <br/>
	 * 
	 * @author askzhao
	 */
	public void notifyDataSetChanged() {
		toFirst();
//		if (mImgList != null && mImgList.size() > 0) {
//			int position = mViewFlipper.getDisplayedChild();
//			if (position == 0) {
//				index_notice_tv.setText(mImgList.get(0).title);
//			} else {
//				index_notice_tv.setText(mImgList.get(0).title);
//				mViewFlipper.showNext();
//			}
//			
//		}

	}

	

	private float dertaY = 0;
	private float lastY = 0;
	private float dertaX = 0;
	private float lastX = 0;

	/*
	 * (non-Javadoc) 避免父控件拦截touch事件
	 */
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			dertaY = 0;
			lastY = ev.getY();
			dertaX = 0;
			lastX = ev.getX();
			break;
		case MotionEvent.ACTION_MOVE:
			dertaY = ev.getY() - lastY;
			dertaX = ev.getX() - lastX;
			lastX = ev.getX();
			lastY = ev.getY();
			break;
		default:
			break;
		}

		if (Math.abs(dertaX) > Math.abs(dertaY)) {
			ViewParent parent = getParent();
			while (parent != null) {
				parent.requestDisallowInterceptTouchEvent(true);
				parent = parent.getParent();
			}
		}
		return super.dispatchTouchEvent(ev);
	}

}
